﻿using System;
using System.Diagnostics;
using Common;

namespace Framework
{
    /// <summary>
    /// 监控函数方法执行的时间
    /// </summary>
    public abstract class MethodRunner
    {
        #region "Private Variables"

        private readonly string _componentName;
        private readonly bool _timeMethods;

        #endregion

        /// <summary>
        ///     Instantiate the underlying policies and logging logging
        /// </summary>
        /// <param name="componentName"></param>
        /// <param name="logName"></param>
        /// <param name="timeMethods"></param>
        protected MethodRunner(string componentName, bool timeMethods = true)
        {
            _timeMethods = timeMethods;
            _componentName = componentName;
        }

        protected bool TimeMethods
        {
            get { return _timeMethods; }
        }

        protected string ComponentName
        {
            get { return _componentName; }
        }

        /// <summary>
        ///     Given a method which does not return any data, time and trace the execution of the method
        /// </summary>
        /// <param name="func"></param>
        /// <param name="methodName"></param>
        /// <param name="vars"></param>
        protected virtual void Execute(Action func, string methodName, params object[] vars)
        {
            try
            {
                Stopwatch stopWatch = null;
                if (_timeMethods && !String.IsNullOrEmpty(methodName))
                {
                    stopWatch = Stopwatch.StartNew();
                }

                func();

                if (stopWatch != null)
                {
                    stopWatch.Stop();

                    LogHelper.Logger.Trace(String.Format("{0}.{1}", _componentName, methodName), stopWatch.Elapsed);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error(String.Format("Error in {0}:{1}. {2}.", _componentName, methodName, ex.ToString()));
                throw;
            }
        }
    }
}